﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class PerformanceCheckFragmentedClusteredIndexes : IssueTypeCheckBase
    {

        public PerformanceCheckFragmentedClusteredIndexes()
        {
            IssueTypeId = 6001;
        }

        public override void Check()
        {
            HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
            Issue issue;

            // Get all Service instance that has ServiceTypeID 1

            var QryIndex = from i in dc.Indexes

                           where (i.IndexType == "CLUSTERED INDEX") && (i.IndexSize > 500) && i.Fragmentation > 50

                           select i;

            // Check number of Logins for each instance    

            foreach (var item in QryIndex)
            {
                
                //Get Issuetype object

                issue = new Issue();

                //Get Issuetype object  And return first issue Id
                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                issue.IssueType = issueType;
                issue.TargetId = item.IndexID;

                
                issue.Description = issueType.Description.Replace("{DatabaseName}", item.Table.Database.DatabaseName).Replace("{IndexName}", item.IndexName).Replace("{TableName}",item.Table.TableName);

                dc.Issues.InsertOnSubmit(issue);




            }


            dc.SubmitChanges();



        }



    }

}
